


#include "qe_device.h"
#include "qelib.h"



#define FLASH_LOGDOMAIN         "flash"
#define flash_debug(...)  	    qelog_debug(FLASH_LOGDOMAIN, __VA_ARGS__)
#define flash_info(...)   	    qelog_info(FLASH_LOGDOMAIN, __VA_ARGS__)
#define flash_warning(...)       qelog_warning(FLASH_LOGDOMAIN, __VA_ARGS__)
#define flash_error(...)  	    qelog_error(FLASH_LOGDOMAIN, __VA_ARGS__)


#define CONFIG_FLASH_TEST	0


static qe_ret spi_flash_status(struct qe_spi_device *spi, qe_u8 *status)
{
	qe_u8 cmd = QE_SPIF_CMD_READ_SR;
	return qe_spi_send_recv(spi, &cmd, 1, status, 1);
}

static qe_unused qe_ret is_spiflash_busy(char *spidev)
{
	qe_u8 status;
	qe_ret ret;
	struct qe_spi_device *spi;

	spi = (struct qe_spi_device *)qe_dev_find(spidev);
	if (!spi) {
		return qe_err_common;
	}

	ret = spi_flash_status(spi, &status);
	if (ret != qe_ok) {
		return ret;
	}

	return (status & QE_SPIF_SR_BUSY);
}

#if (CONFIG_FLASH_TEST == 1)
static qe_ret flash_test_once(qe_spif_dev *flash, qe_u32 address)
{
#define FLASH_TEST_BUFSZ	512
	int i;
	char txbuf[FLASH_TEST_BUFSZ];
	char rxbuf[FLASH_TEST_BUFSZ];

	for (i=0; i<FLASH_TEST_BUFSZ; i++) {
		txbuf[i] = i;
	}

	flash_debug("read");
	qe_spif_read(flash, address, FLASH_TEST_BUFSZ, rxbuf);
	qehex_debug(FLASH_LOGDOMAIN, rxbuf, FLASH_TEST_BUFSZ);

	flash_debug("erase");
	qe_spif_erase(flash, address, FLASH_TEST_BUFSZ);
	flash_debug("read");
	qe_spif_read(flash, address, FLASH_TEST_BUFSZ, rxbuf);
	qehex_debug(FLASH_LOGDOMAIN, rxbuf, FLASH_TEST_BUFSZ);

	flash_debug("write");
	qe_spif_write(flash, address, FLASH_TEST_BUFSZ, txbuf);
	flash_debug("read");
	qe_spif_read(flash, address, FLASH_TEST_BUFSZ, rxbuf);
	qehex_debug(FLASH_LOGDOMAIN, rxbuf, FLASH_TEST_BUFSZ);
	return qe_ok;
}

static qe_ret flash_test(qe_spif_dev *flash)
{
	qe_u32 addr;
	qe_spif_chip info;

	qe_dev_ioctl((qe_dev *)flash, QE_SPIF_CTRL_GET_CHIPINFO, &info);
	flash_debug("info %d %d", info.capacity, info.sector_size);

	addr = 0x00000000;
	flash_debug("test at 0x%x", addr);
	flash_test_once(flash, addr);

	addr = info.capacity - info.sector_size;
	flash_debug("test at 0x%x", addr);
	flash_test_once(flash, addr);
	return qe_ok;
}
#endif

static qe_unused qe_init int qspi_flash_init(void)
{
    qe_spif_dev *dev;

	qe_spif_chip info = {
		.name = "MT25QU256",
		.mf_id = JEDEC_ID_MICRON,
		.mt_id = 0xBB,
		.capacity_id = 0x19,
		.capacity = 32 * 1024 * 1024,
		.sector_size = 64 * 1024,
		.erase_sector_cmd = 0x20,
		.write_mode = QE_SPIF_WM_PAGE_256B,
		.flag = FLASH_F_4BYTE,
	};

    dev = qe_spif_probe("flash0", "spi0.0", &info);
    if (!dev) {
        flash_error("spi0.0 probe flash error");
        return -1;
    }

#if (CONFIG_FLASH_TEST == 1)
	flash_test(dev);
#endif

    return 0;
}
//QE_DEVICE_EXPORT(qspi_flash_init);
